<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/07/15 9:29
 * Desc: 公共方法
 */
class Model_Api_V2_Common extends ORM
{

    /**
     * @param $type
     * @param $key
     * @param string $value
     * @param $time int
     * @return bool|mixed
     * 缓存设置与获取
     */
    public static function cache($type, $key, $value = '',$time = 3600)
    {
        $cache_dir = CACHE_DIR . 'uniapp/api';
        if (!file_exists($cache_dir)) {
            if ( ! mkdir($cache_dir, 0755, true) && ! is_dir($cache_dir)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $cache_dir));
            }
        }
        $cache = Cache::instance('uniapp');
        //获取缓存
        if ($type == 'get') {
            return $cache->get($key, '');
        } //设置缓存
        else if ($type == 'set')
        {
            return $cache->set($key, $value, $time);
        }
    }

    /**
     * @function 创建uuid
     */
    public static function create_uuid()
    {
        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
            mt_rand( 0, 0xffff ),
            mt_rand( 0, 0x0fff ) | 0x4000,
            mt_rand( 0, 0x3fff ) | 0x8000,
            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
        );
    }

    /**
     * @function 获取图片base64验证码
     * @param null $param
     * @return array
     */
    public static function verify_code_image_base64($param=null)
    {
        // 设置验证码生成几位
        $num = 4;
        // 设置宽度
        $width = 100;
        // 设置高度
        $height = 30;
        //生成验证码，也可以用mt_rand(1000,9999)随机生成
        $str='ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);返回字符串的一部分

        // 设置头部
        header("Content-type: image/png");

        // 创建图像（宽度,高度）
        $img = imagecreate($width,$height);

        //创建颜色 （创建的图像，R，G，B）
        $GrayColor = imagecolorallocate($img,230,230,230);
        $BlackColor = imagecolorallocate($img, 0, 0, 0);
        $BrColor = imagecolorallocate($img,52,52,52);

        //填充背景（创建的图像，图像的坐标x，图像的坐标y，颜色值）
        imagefill($img,0,0,$GrayColor);

        //设置边框
        //imagerectangle($img,0,0,$width-1,$height-1, $BrColor);

        //随机绘制两条虚线 五个黑色，五个淡灰色
        $style = array ($BlackColor,$BlackColor,$BlackColor,$BlackColor,$BlackColor,$GrayColor,$GrayColor,$GrayColor,$GrayColor,$GrayColor);
        imagesetstyle($img, $style);
        imageline($img,0,mt_rand(0,$height),$width,mt_rand(0,$height),IMG_COLOR_STYLED);
        imageline($img,0,mt_rand(0,$height),$width,mt_rand(0,$height),IMG_COLOR_STYLED);

        //随机生成干扰的点
        for ($i=0; $i < 100; $i++) {
            $PointColor = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
            imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$PointColor);
        }

        //将验证码随机显示
        for ($i = 0; $i < $num; $i++) {
            $x = ($i*$width/$num)+mt_rand(5,12);
            $y = mt_rand(5,10);
            imagestring($img,14,$x,$y,substr($code,$i,1),$BlackColor);
        }

        ob_start ();
        //$im是你自己创建的图片资源
        imagepng ($img);
        $image_data = ob_get_contents ();
        ob_end_clean ();
        $image_data_base64 = "data:image/png;base64,". base64_encode ($image_data);
        return array(
            'base64'=> $image_data_base64,
            'code' => $code
        );
    }

    /**
     * @function 验证图片验证码
     * @param $key
     * @param $code
     * @return bool
     */
    public static function verify_image_code($key,$code)
    {
        if(!$key || !$code)
        {
            return false;
        }

        $cache_code = Model_Api_V2_Common::cache('get', $key);
        // 不区分大小写
        $code = strtolower($code);
        $cache_code = strtolower($cache_code);
        if($cache_code === $code)
        {
            return true;
        }
        return false;
    }


    /**
     * 获取会员头像
     * @param $url
     * @return mixed|string|string[]|null
     */
    public static function get_member_header_pic($url){
        // 判断url开头是否为`//`开头的地址
        if($url) {
            $first = substr($url,0,2);
            if($first == '//') { // 直接添加http
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https:' : 'http:';
                return $http_type.$url;
            } else {
                return Model_Api_V2_System::reorganized_resource_url($url);
            }
        } else {  // 默认头像
            return Model_Api_V2_System::reorganized_resource_url(Common::member_nopic());
        }
    }

    /**
     * 单一查询
     * @param $table
     * @param int $where
     * @param string $fields
     * @param bool|false $getResult
     * @return bool
     */
    public static function st_query($table, $where = 1, $fields = '*', $getResult = false)
    {
        $bool = false;
        $rs = DB::select($fields)->from($table)->where($where)->execute()->current();
        if (!empty($rs))
        {
            $bool = !$getResult ? true : $rs;
        }
        return $bool;
    }

    /**
     * 更新数据
     * @param $table
     * @param $update
     * @param $where
     * @return int|object
     */
    public static function st_update($table, $update, $where)
    {
        $bool = 0;
        $row = DB::update($table)->set($update)->where($where)->execute();
        if ($row > 0)
        {
            $bool = $row;
        }
        return $bool;
    }

    /**
     * 添加数据
     * @param $table
     * @param $data
     * @return object
     */
    public static function st_insert($table, $data)
    {
        $rs = DB::insert($table, array_keys($data))->values(array_values($data))->execute();
        return $rs;
    }

    /**
     * @function
     * @function 返回需要的值
     * @param $filed string 需要的值的键值字符串
     * @param $data array 全部数组
     * @return array
     */
    public static function res_data($field,$data)
    {
        $rData = explode(',',$field);
        $return = array();
        foreach ($rData as $v)
        {
            $return[$v] = '';
            if(isset($data[$v]))
            {
                $return[$v] = $data[$v];
            }
        }
        return $return;
    }

    /**
     *  抛出验证异常
     * @param $validation
     * @return void
     */
    public static function throw_validation_exception($validation)
    {
        if (!$validation->check()) {
            $errors = $validation->errors('default');
            $keys   = array_keys($errors);
            throw new Exception(__("{$errors[$keys[0]]}"));
        }
    }
}